$(document).ready(function() {
	userPage.init();
});
var userPage = {
	listUrl : _webApp + '/system/product/list',
	saveUrl : _webApp + '/system/product/save',
	delUrl : _webApp + '/system/product/delete',
	userRoleUrl : _webApp + '/system/product/getUserRole',
	chooseRoleUrl : _webApp + '/system/product/getChooseRoles',
	/**
	 * 初始化
	 */
	init : function() {
		this.initGrid();
		this.initSearch();
		this.initBtns();
		this.adaptive();
	},
	/**
	 * 初始化数据grid
	 */
	initGrid : function() {
		this.dataGrid = $('#data_gird').datagrid({
			url : this.listUrl,
			sortName : "id",
			sortOrder : "asc",
			idField : "id",
			height : this.autoHeight(1),
			nowrap : true,
			pagination : true,
			rownumbers : true,
			pageSize : 20,
			autoRowHeight : false,
			singleSelect : true,
			checkOnSelect : false,
			selectOnCheck : false,
			columns : [[{
				checkbox : true
			},
			{
				field : 'id',
				title : 'ID',
				sortable : true,
				hidden : true
			},
			{
				field : 'loginName',
				title : '账号',
				width:100,
				sortable : true
			},
			{
				field : 'name',
				title : '用户名称',
				width:120,
				sortable : true
			},
            {
                field : 'roleNames',
                title : '角色',
                sortable : true
            },
			{
				field : 'email',
				title : 'Email',
				sortable : true
			},
			{
				field : 'phone',
				title : '电话',
				sortable : true
			},
			{
				field : 'qq',
				title : 'QQ',
				sortable : true
			}
			]],
			toolbar : [{
				text : '新增',
				iconCls : 'i_add',
				disabled : !p_create,
				handler : function() {
					userPage.add();
				}
			}, {
				text : '删除',
				iconCls : 'i_delete',
				disabled : !p_delete,
				handler : function() {
					userPage.del();
				}
			}],
			onClickRow : function(index, row) {
				userPage.viewUserRow(row);
			}
		});
		this.extraRoleGird = $('#extra_role_gird').datagrid({
			url : this.userRoleUrl,
			sortName : "id",
			sortOrder : "asc",
			idField : "id",
			height : 200,
			width : 500,
			rownumbers : true,
			singleSelect : true,
			columns : [[{
				field : 'id',
				title : 'ID',
				hidden : true
			}, {
				field : 'name',
				title : '名称',
				width : 150
			}, {
				field : 'role',
				title : '标识',
				width : 200
			},{
				field : 'operate',
				title : '',
				width : 100,
				align : 'center',
				formatter : function(value, row, index) {
					var html='';
					if(p_update){
						html+=	'<a class="operate_btn" href="javascript:userPage.delRole();">删除</a>';
					}
					return html;
				}
			}]],
			toolbar : [{
				text : '添加角色',
				iconCls : 'i_column_add',
				disabled : !p_update,
				handler : function() {
					userPage.addRole();
				}
			}]
		});
		this.editPanle = $('#edit_panle').panel({
			title : '角色详细信息：',
			height : this.autoHeight(2),
			tools : [{
				iconCls : 'icon-add',
				handler : function() {
					alert('new');
				}
			}, {
				iconCls : 'icon-save',
				handler : function() {
					alert('save');
				}
			}]
		});
		$(window).resize(function() {
			userPage.dataGrid.datagrid('resize', {
				height : autoHeight(),
			});
		});
	},
	autoHeight : function(type) {
		var dataHeight = 360;
		switch (type) {
			case 1:
				return dataHeight;
				break;
			case 2:
				return document.documentElement.clientHeight - $("#search").outerHeight(true) - dataHeight - $("#buttons").outerHeight(true);
				break;
		}
	},
	/**
	 * 查看用户详细数据
	 */
	viewUserRow:function(row){
		resetForm($('form',this.editPanle));
		$('form', this.editPanle).form('load', row);
		userPage.switchEditPanle(2);
		this.extraRoleGird.datagrid('load', {
			userId : row.id
		});
		this.editPanle.panel({
			title : row.loginName + "[" + row.name + "]"
		});						
	},
	/**
	 * 自适应窗口大小
	 */
	adaptive : function() {
		$(window).resize(function() {
			userPage.dataGrid.datagrid('resize', {
				height : userPage.autoHeight(1),
			});
			userPage.editPanle.panel('resize', {
				height : userPage.autoHeight(2),
			});
		});
	},
	/**
	 * 初始化按钮绑定
	 */
	initBtns : function() {
		$("#save-btn").click(function() {
			userPage.ajaxToSave();
		});
		$("#refresh-btn").click(function() {
			var row = userPage.dataGrid.datagrid('getSelected');
			if(row){
				userPage.viewUserRow(row);
			}
			
		});
	},
	/**
	 * 初始化搜索栏
	 */
	initSearch : function() {
		// 对搜索按钮和单选框绑定点击搜索事件
		$("#search .search_btn,#search input:radio").click(function() {
			userPage.search();
		});
		// 对搜索栏输入框绑定回车搜索事件
		$("#search input").keydown(function(event) {
			if (event.keyCode == 13) {
				userPage.search();
			}
		});
	},
	/**
	 * 搜索
	 */
	search : function() {
		var searchData = $("#search_form").serializeJson();
		userPage.dataGrid.datagrid('load', searchData);
		//清楚所有选中项，防止出现删除后的项目依然存在于选中项中
		this.dataGrid.datagrid("clearChecked");
	},
	/**
	 * 刷新
	 */
	refresh : function() {
		this.dataGrid.datagrid("reload");
		//清楚所有选中项，防止出现删除后的项目依然存在于选中项中
		this.dataGrid.datagrid("clearChecked");
	},
	add:function(){
		this.switchEditPanle(2);
		resetForm($('form',this.editPanle));
		this.editPanle.panel({
					title : '新增用户'
				});
		this.extraRoleGird.datagrid('load', {
					userId : ""
		});
	},
	/**
	 * ajax储存
	 */
	ajaxToSave : function() {
		var rows = this.extraRoleGird.datagrid("getRows");
		var roleIds =  "";

		if (rows) {
			for (var i in rows) {
				roleIds += rows[i].id + ",";
			}
			roleIds = roleIds.substr(0,roleIds.length-1);
		}
		var options = {
			url : this.saveUrl,
			beforeSubmit : this.validate, //表单元素有效性验证
			data : {
				roleIds : roleIds
			},
			success : function(data) {
				if ( typeof data == 'object') {
				if (data.result == "success") {
					messagerShow("保存成功");
					userPage.switchEditPanle(1);
				} else {
					$.messager.alert("结果", "保存错误");
				}
				userPage.refresh();
				} else if ( typeof data == 'string') {
				if (data.indexOf("用户权限不足") >= 0) {
					$.messager.alert("警告", "用户权限不足");
				}
			}
			}
		};
		$('form', this.editPanle).ajaxSubmit(options);
	},
	/**
	 *表单元素有效性验证，使用jquery.validate插件
	 */
	validate : function(arr, $form, options) {
		//jquery.validate插件无及时验证方法，只能通过提交触发
		$form.validate({
			debug : true,
			rules: {
					loginName: {
      					required: true
    				},
					password: {
      					required: false
    				},
					salt: {
      					required: false
    				},
					name: {
      					required: true
    				},
					email: {
      					required: false
    				},
					phone: {
      					required: false
    				},
					qq: {
      					required: false
    				},
					status: {
      					required: true
    				},
  			}
		});
		$form.submit();
		return $form.valid();
	},
	/**
	 * 批量删除
	 */
	del : function() {
		var row = this.dataGrid.datagrid('getSelected');
		if (row) {
			var html = '<span class="cRed">' + row.loginName + '[' + row.name + ']</span>';
			$.messager.confirm('确认信息？', '确认删除：' + html, function(r) {
				if (r) {
					var ids = new Array();
					ids.push(row.id);
					userPage.ajaxToDelte(ids);
				}
			});
		} else {
			$.messager.alert('提示', '请选择需要删除的数据!');
		}
	},
	/**
	 * ajax删除
	 */
	ajaxToDelte : function(ids) {
		var url = this.delUrl;
		$.post(url, {
			ids : ids
		}, function(data) {
			if ( typeof data == 'object') {
			if (data.result == "success") {		
				messagerShow("成功删除"+ids.length+"条记录");
				userPage.switchEditPanle(1);
			} else {
				$.messager.alert("结果", "删除错误");
			}
			userPage.refresh();
			} else if ( typeof data == 'string') {
				if (data.indexOf("用户权限不足") >= 0) {
					$.messager.alert("警告", "用户权限不足");
				}
			}
		});
	},
	/**
	 * 切换编辑面板
	 */
	switchEditPanle:function(type){
		switch (type) {
			case 1:
				$("#edit_panle .norecord").show();
				$("#edit_panle .record").hide();
				userPage.editPanle.panel({
					title : "用户详细信息"
				});
				break;
			case 2:
				$("#edit_panle .record").show();
				$("#edit_panle .norecord").hide();
				break;
		}
	},
	/**
	 * 增加权限
	 */
	addRole : function() {
		if (this.roleGrid) {
			//清楚所有选中项，防止出现删除后的项目依然存在于选中项中
			this.roleGrid.datagrid("clearChecked");
			this.roleGrid.datagrid('load');
		}else{
			this.initRoleGrid();
		}
		var $thisDialog = $('#role_dialog');
		$thisDialog.dialog({
			title : "添加用户角色",
			width : 560,
			height : 353,
			modal : true,
			resizable : true,
			buttons : [{
				text : '确定',
				handler : function() {
					//清空原有数据
					userPage.extraRoleGird.datagrid('loadData', { total: 0, rows: [] });
					var rows = userPage.roleGrid.datagrid("getChecked");
					for(var i in rows){
						userPage.extraRoleGird.datagrid("appendRow",rows[i]);
					}
					$thisDialog.dialog("close");
				}
			}, {
				text : '取消',
				handler : function() {
					$thisDialog.dialog("close");
				}
			}]
		});
	},
	delRole : function() {
		var gird = this.extraRoleGird;
		var row = gird.datagrid('getSelected');
		if (row) {
			var index = gird.datagrid('getRowIndex', row);
			gird.datagrid('deleteRow', index);
		}
	},
	initRoleGrid : function() {
		this.roleGrid = $('#role_gird').datagrid({
			url : this.chooseRoleUrl,
			sortName : "id",
			sortOrder : "asc",
			idField : "id",
			height : 280,
			nowrap : true,
			pagination : true,
			rownumbers : true,
			pageSize : 20,
			striped : true,
			autoRowHeight : false,
			columns : [[{
				checkbox : true
			}, {
				field : 'id',
				title : 'ID',
				sortable : true,
				hidden : true,
				formatter : function(value, row, index) {
					if($.inArray(row.id,userPage.hasRoles())>=0){
						userPage.roleGrid.datagrid('checkRow', index);
					}					
				}
			}, {
				field : 'name',
				title : '名称',
				width : 100,
				sortable : true
			}, {
				field : 'role',
				title : '标识',
				width : 120,
				sortable : true
			}, {
				field : 'description',
				title : '描述',
				sortable : true
			}]]
		});
	},
	/**
	 * 获取已经选择的角色ID数组
	 */
	hasRoles:function(){
		var rows = this.extraRoleGird.datagrid("getRows");
		var rolesIds = new Array();
		for(var i in rows){
			rolesIds.push(rows[i].id);
		}
		return rolesIds;
	},
};

